<?php
namespace App\Plugins\Sms;

/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2016/10/27
 * Time: 15:43
 */
class SendInfo{
    /*
     * 获取URL数据
     */
    public function curl($url, $data = null)
    {
        //初始化
        $curl = curl_init();
        //设置选项，包括URL
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            //POST数据
            curl_setopt($curl, CURLOPT_POST, 1);
            //POST变量
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行并获取HTML文档内容
        $output = curl_exec($curl);
        //释放curl句柄
        curl_close($curl);
        return $output;

    }
    /*
     *  发送短信接口
     *  1、您正在易微链找回密码，验证码：888999，如非本人操作请忽略，30分钟内有效
        2、客户被误领申诉：客户“XX昵称X，加好友时间2016-10-09 15:30:30”被同事（xxxx 13818191760）误领，请将客户关系转给（XXXX 13800000000）
        3、UIN:XXXXXX的微信号异常，请马上处理!
        4、您的易微链账号已创建，密码：xxxxxx，请尽快登陆后台修改。
     */
    //action=send&userid=12&account=账号&password=密码&mobile=15023239810,13527576163&content=内容&sendTime=&extno=
    public function Send($code,$_filter=[],$mobile = "",$sendTime = null, $extno = null){//对方发送过来的验证码
        if (empty($mobile)){
            return $this->json(1,'error','手机号码不能为空');
        }if (empty($code)){
            return $this->json(5,'error','code不能为空');
        }
        $config = include app_path('/Plugins/Sms/SendInfoConfig.php');
        if ($code == 1){//忘记密码找回密码
            if (empty($_filter['sendNum'])){
                return $this->json(2,'error','验证码不能为空');
            }
            $content = str_replace('&a',$_filter['sendNum'],$config['contentFindPw']);
            $content = str_replace('&t',$_filter['usefulTime'],$content);
        }elseif($code == 2){//客户被误领申述
            if (empty($_filter['customer'])||empty($_filter['addTime'])||empty($_filter['colleague'])||empty($_filter['colleagueNum'])||empty($_filter['sendTo'])||empty($_filter['sendToNum'])){
                return $this->json(3,'error','请填写完整参数');
            }
            $content = $config['contentMistake'];
            $content = str_replace('&b',$_filter['customer'],$content);
            $content = str_replace('&c',$_filter['addTime'],$content);
            $content = str_replace('&d',$_filter['colleague'],$content);
            $content = str_replace('&e',$_filter['colleagueNum'],$content);
            $content = str_replace('&f',$_filter['sendTo'],$content);
            $content = str_replace('&g',$_filter['sendToNum'],$content);
        }elseif ($code == 3){//微信异常
            if (empty($_filter['WxNum'])){
                return $this->json(4,'error','微信号不能为空');
            }
            $content = $config['contentAbnormal'];
            $content = str_replace('&h',$_filter['WxNum'],$content);
        }elseif ($code == 4){//创建账号
            if (empty($_filter['password'])){
                return $this->json(5,'error','密码不能为空');
            }
            $content = $config['content_establish'];
            $content = str_replace('&i',$_filter['password'],$content);
            $content = str_replace('&j',$_filter['alias'],$content);
        }
        $data = [
            'mobile' => $mobile,
            'content'=>$content,
            'userid' =>$config['id'],
            'sendTime'=> $sendTime,
            'extno' => $extno,
            'account' =>$config['username'],
            'password' =>$config['password'],
        ];
        $xmlData = $this->curl($config['sendUrl'],$data);
        //将XML数据转化为JSON数据
        return $this->xmlToJson($xmlData,'send.txt','Success');

    }
    /**
     * 余额及已发送量查询接口
     */

    public function getInfo(){
        $config = include app_path('/Plugins/Sms/SendInfoConfig.php');
        $data = [
            'userid' =>$config['id'],
            'account' =>$config['username'],
            'password' =>$config['password'],
        ];
        $xmlData = $this->curl($config['getInfoUrl'],$data);
        //将XML数据转化为JSON数据
        return $this->xmlToJson($xmlData,'getInfo.txt','Sucess');
    }

    /*
     * 非法关键字查询
     */
    public function search($_filter = ""){
        $config = include app_path('/Plugins/Sms/SendInfoConfig.php');
        $data = [
            'content'=>$_filter,
            'userid' =>$config['id'],
            'account' =>$config['username'],
            'password' =>$config['password'],
        ];
        $xmlData = $this->curl($config['searchUrl'],$data);
        //将XML数据转化为JSON数据
        return $this->xmlToJson($xmlData,'search.txt','Success');
    }

    /*
    * 状态报告接口
    */
    public function state($_filter = 4000){
        try {
            $config = include app_path('/Plugins/Sms/SendInfoConfig.php');
            $data = [
                'statusNum' => $_filter,
                'userid' => $config['id'],
                'account' => $config['username'],
                'password' => $config['password'],
            ];
            $xmlData = $this->curl($config['stateUrl'], $data);
            //将XML数据转化为JSON数据
            libxml_disable_entity_loader(true);
            $xmlstring = simplexml_load_string($xmlData, 'SimpleXMLElement', LIBXML_NOCDATA);
            $val = json_encode($xmlstring);
            return $val;
        }catch (\Exception $ex){
            file_put_contents(storage_path("logs/state.txt"),$ex.PHP_EOL,FILE_APPEND);
        }
    }
    /*
    * 上行接口
    */

    public function up(){
        try {
            $config = include app_path('/Plugins/Sms/SendInfoConfig.php');
            $data = [
                'userid' => $config['id'],
                'account' => $config['username'],
                'password' => $config['password'],
            ];
            $xmlData = $this->curl($config['upUrl'], $data);
            //将XML数据转化为JSON数据
            libxml_disable_entity_loader(true);
            $xmlstring = simplexml_load_string($xmlData, 'SimpleXMLElement', LIBXML_NOCDATA);
            $val = json_encode($xmlstring);
            return $val;
        }catch (\Exception $ex){
            file_put_contents(storage_path("logs/up.txt"),$ex.PHP_EOL,FILE_APPEND);
        }
    }

    /*
    * 密码修改接口
    */
    public function changePwd($_filter=[]){
        $config = include app_path('/Plugins/Sms/SendInfoConfig.php');
        if (empty($_filter['newpwd'])){
            return $this->json(1,'error','请输入密码');
        }
        if (empty($_filter['renewpwd'])){
            return $this->json(2,'error','请再次输入密码');
        }
        $data = [
            'newpwd' => $_filter['newpwd'],
            'renewpwd'=>$_filter['renewpwd'],
            'userid' =>$config['id'],
            'account' =>$config['username'],
            'password' =>$config['password'],
        ];
        $xmlData = $this->curl($config['changePwdUrl'],$data);
        //将XML数据转化为JSON数据
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xmlData, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_encode($xmlstring);
        $val_arr = json_decode($val,true);
        //$checkCounts = implode(' ',$val_arr['checkCounts']);
        return $this->xmlToJson($xmlData,'changePwd.txt','Sucscess');
    }

     /*
     * 输出json格式数据
     */
    public function json($code = 0 ,$msg = '', $arr = []){
        $data = [
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$arr
        ];
        return json_encode($data);
    }

    /*
     * 将XML转化为JSON格式数据
     */
    public function xmlToJson($xmlData,$logName,$message){
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xmlData, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_encode($xmlstring);
        $val_arr = json_decode($val,true);
        if($val_arr['returnstatus'] != $message){
            $val_arr = $this->arrToStr($val_arr);
            file_put_contents(storage_path("logs/{$logName}"),$val_arr.PHP_EOL,FILE_APPEND);
        };
        return $val;
    }
    /*
     * 重组数据
     */
    public function arrToStr($arr = []){
        if (is_array($arr)){
            foreach ($arr as $key =>$value){
                if (is_array($value)){
                    if (empty($value)){
                        unset($arr[$key]);
                    }elseif (!empty($value)){
                        $arr[$key] = implode(',',$value);
                    }
                    foreach ($arr as $k=>$v){
                        $arr[$k] = $k.':'.$v;
                        $str = implode(' ',$arr);
                    }
                    return $str;
                }
            }
            foreach ($arr as $one=>$two){
                $arr[$one] = $one.':'.$two;
                $str = implode(' ',$arr);
            }
            return $str;
        }
    }
}